package com.dst.smart.handler.disposer;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dst.smart.app.MainActivity;
import com.dst.smart.handler.entity.SemanticResult;
import com.dst.smart.handler.entity.ServiceType;
import com.dst.smart.music.MusicPlayMedia;
import com.dst.smart.player.entity.SongPlayInfo;
import android.content.Context;
import android.util.Log;

/**
 *故事
 * 讲个故事
 我想听安徒生写的故事
 换一个故事吧
 *
 * author <a href="http://www.xfyun.cn">讯飞开放平台</a>
 * date 2016年9月5日 下午4:58:10
 *
 */
public class StoryDisposer extends Disposer{
	private static final String KEY_URL = "playUrl";
	
	public StoryDisposer(Context context) {
		super(context);
	}
	
	@Override
	public void disposeResult(final SemanticResult semanticResult) {
		final List<SongPlayInfo> playList = new ArrayList<SongPlayInfo>();
		try {
			if (semanticResult != null) {
				if (MainActivity.musicIsSong) {
					String answer = semanticResult.getAnswerText();
					Log.e("text", "Story" + answer);
					JSONArray result = semanticResult.getResult();
					if (result == null || result.length() == 0) {
						getPlayController().playURLList(semanticResult.getUUID(), null);
						if (answer.length() > 0) {
							getPlayController().playText(semanticResult.getUUID(), semanticResult.getAnswerText(), true, null, null);
						} else {
							getPlayController().playText(semanticResult.getUUID(), "", true, null, null);
						}
					} else {
						for (int i = 0; i < result.length(); i++) {
							JSONObject newsJson = result.optJSONObject(i);

							String url = newsJson.getString(KEY_URL);

							SongPlayInfo playInfo = new SongPlayInfo();

							if (i == 0) {
								playInfo.setAnswerText(semanticResult.getAnswerText());
							} else {
								playInfo.setAnswerText("***");
							}
							playInfo.setPlayUrl(url);
							playList.add(playInfo);
						}
						//getPlayController().playSongList(semanticResult.getUUID(), playList,false);
						try {
							if (MusicPlayMedia.getInstansMedia() == null) {
								new MusicPlayMedia(mContext, "");
							}
							MusicPlayMedia.getInstansMedia().playURLList(playList);
							MusicPlayMedia.getInstansMedia().setFileName(1,
									playList.get(0).getPlayUrl(), 1);
							MusicPlayMedia.getInstansMedia().play();
							if (answer.length() > 0) {
								//先播放標題
								getPlayController().playURLList(semanticResult.getUUID(), null);
								getPlayController().playText(semanticResult.getUUID(), semanticResult.getAnswerText(), true, "", null);
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						//sendAiuiData("故事", "poetry", result.toString());
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean canHandle(ServiceType type){
		return (type == ServiceType.STORY);
	}

}
